package database

import (
	"fmt"
	"log"
	"os"
	"time"
	"xcloud-oauth2-server/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// NewDatabase returns a gorm.DB struct
func NewDatabase(cfg *config.Config) (*gorm.DB, error) {
	if cfg.Database.Type == "mysql" {
		//dsn := "root:root@tcp(192.168.1.11:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			cfg.Database.User,
			cfg.Database.Password,
			cfg.Database.Host,
			cfg.Database.Port,
			cfg.Database.DatabaseName,
		)

		newLogger := logger.New(
			log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
			logger.Config{
				SlowThreshold:             time.Second, // Slow SQL threshold
				LogLevel:                  logger.Info, // Log level
				IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
				Colorful:                  true,        // Disable color
			},
		)

		db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: newLogger,
			//DisableForeignKeyConstraintWhenMigrating: true, //自动创建数据库外键约束
		})
		if err != nil {
			return db, err
		}

		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(cfg.Database.MaxIdleConns)
		sqlDB.SetMaxOpenConns(cfg.Database.MaxOpenConns)

		return db, nil
	}

	//DataBase type not supported

	return nil, fmt.Errorf("Database type %s not supported", cfg.Database.Type)
}
